<?php
namespace Home\Controller;

use Common\Service\Curl;
use Common\Service\WXBizDataCryptAes;
use Think\Controller;
use Think\Log;

class ApiController extends Controller
{
    /**
     * 获取openid ,保存用户数据
     * @return [type] [description]
     */
    public function getopenidbycode()
    {
        $code   = I('code');
        $appid  = C('mini_config')['app_id'];
        $secret = C('mini_config')['app_secret'];

        $url    = "https://api.weixin.qq.com/sns/jscode2session?appid=" . $appid . "&secret=" . $secret . "&js_code=" . $code . "&grant_type=authorization_code";
        $json   = Curl::request("get", $url);
        $res    = json_decode($json);
        $openid = $res->openid;

        if ($openid) {
            $info = M("user")->where(["openid" => $openid])->find();
            if ($info) {
                M("user")->where(["openid" => $openid])->save(['update_time' => time()]);
                exit(json_encode(array('err' => 0, 'msg' => '查询openid成功', 'res' => $openid)));
            } else {
                $arr = [
                    'add_time' => time(),
                    'openid'   => $openid,
                ];
                M("user")->add($arr);
                exit(json_encode(array('err' => 0, 'msg' => '查询openid成功', 'res' => $openid)));
            }

        } else {
            exit(json_encode(array('err' => 1, 'msg' => '查询openid失败', 'res' => 'code过期')));
        }
    }

    /**
     * 获取用户基本信息(此方法暂时没用，获取用户信息是上面的方法，信息由微信小程序获取传递到后台)
     * @return [type] [description]
     */
    public function userinfo()
    {
        $encryptedData = I('encryptedData');
        $iv            = I('iv');
        $code          = I('code');

        $appid  = C('mini_config')['app_id'];
        $secret = C('mini_config')['app_secret'];

        $url        = "https://api.weixin.qq.com/sns/jscode2session?appid=" . $appid . "&secret=" . $secret . "&js_code=" . $code . "&grant_type=authorization_code";
        $json       = Curl::request("get", $url);
        $res        = json_decode($json);
        $sessionKey = $res->session_key;
        $openid     = $res->openid;

        if ($openid) {
            $info = M("user")->where(["openid" => $openid])->find();
            if ($info) {
                exit(json_encode(array('err' => 0, 'msg' => '查询openid成功', 'res' => $openid)));
            } else {
                //新增用户信息
                $WXBizDataCrypt = new WXBizDataCryptAes($appid, $sessionKey);
                $errCode        = $WXBizDataCrypt->decryptData($encryptedData, $iv, $data);

                Log::write('@@111' . $errCode);
                Log::write('@@222' . $data);
                if ($errCode == 0) {
                    $userInfo = json_decode($data, true);
                    $arr      = array(
                        'nickname' => $userInfo['nickName'],
                        'headimg'  => $userInfo['avatarUrl'],
                        'province' => $userInfo['province'],
                        'country'  => $userInfo['country'],
                        'city'     => $userInfo['city'],
                        'sex'      => $userInfo['gender'],
                        'add_time' => time(),
                        'openid'   => $openid,
                    );
                }

                M("user")->add($arr);
                exit(json_encode(array('err' => 0, 'msg' => '查询openid成功', 'res' => $openid)));
            }

        } else {
            exit(json_encode(array('err' => 1, 'msg' => '查询openid失败', 'res' => 'code过期')));
        }
    }

    /**
     * 更新用户信息
     */
    public function userinfo_update()
    {
        $openid   = I('openid');
        $userInfo = I('userinfo', '', '');
        //替换转义字符
        $userInfo = str_replace(array("\r\n", "\r", "\n"), "", $userInfo);
        Log::write('@@userInfo' . $userInfo);
        $userInfo = json_decode($userInfo, true);
        Log::write('@@userInfo' . $userInfo['nickName']);
        $r = M("user")->where(["openid" => $openid])->find();
        if ($r['nickname'] == '') {
            $arr = [
                'nickname'    => $userInfo['nickName'],
                'headimg'     => $userInfo['avatarUrl'],
                'province'    => $userInfo['province'],
                'country'     => $userInfo['country'],
                'city'        => $userInfo['city'],
                'sex'         => $userInfo['gender'],
                'update_time' => time(),
            ];

            $res = M('user')->where(['openid' => $openid])->save($arr);
            Log::write("update_res", $res);
        }
    }

    /**
     * 获取首页模版列表
     * @return [type] [description]
     */
    public function alist()
    {
        $type = I('type', '1');
        $res  = M('temp_info')->where(['type' => $type,'is_show'=>1])->order('sort asc')->select();

        foreach ($res as $k => $v) {
            $res[$k]['img_url'] = C('DOMAIN') . $v['img_url'];
        }

        exit(json_encode(array('err' => 0, 'msg' => '查询成功', 'res' => $res)));
    } 

    /**
     * 是否开启支付
     */
    public function is_pay()
    {
        $r = M('seeting')->where(['id'=>1])->find();
        exit(json_encode(array('err' => 0, 'msg' => '查询成功', 'res' => $r['value'])));
    }

    //用户当前模板是否已经支付
    public function payinfo(){
        $openid = I('openId');
        $tempId = intval(I('tmpId')); //模板id

        //是否已经全部支付
        $r = M("payorder")->where(["openid"=>$openid,'pay_type'=>1,'pay_status'=>1])->find();

        if($r){
            exit(json_encode(array('err' => 0, 'msg' => '查询成功', 'res' => true)));
        }

        //是否针对该模板支付
        $rr = M("payorder")->where(["openid"=>$openid,'pay_type'=>2,'pay_status'=>1,'temp_id'=>$tempId])->find();
        
        if($rr){
            exit(json_encode(array('err' => 0, 'msg' => '查询成功', 'res' => true)));
        }

        exit(json_encode(array('err' => 0, 'msg' => '查询成功', 'res' => false)));
    }

    public function info(){
        $c = M("user")->count();
        echo $c;
    }
}
